/**
 * 
 */
package com.wistech.search.solr.extend;

import java.io.IOException;
import java.util.Collection;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.OpenBitSet;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;

import com.google.common.collect.Sets;
import com.wistech.commons.utils.spring.SpringContextHolder;
import com.wistech.utils.DocumentUtils;

/**
 * 在线状态过滤器
 * 
 * @author Liuye
 * 
 */
public class OnlineFilter extends Filter {
	public static final String FIELD_NAME = "live_online";
	private static final String KEY = "companyId";
	private final SchemaField field;

	private Collection<String> onlineCompanyIds = Sets.newHashSet();

	public OnlineFilter(IndexSchema schema) {
		ExternalDataContext context = SpringContextHolder
				.getBean("externalDataContext");
		onlineCompanyIds.addAll(context.getOnlineCompanyIds());
		this.field = schema.getField(KEY);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.lucene.search.Filter#getDocIdSet(org.apache.lucene.index.
	 * IndexReader)
	 */
	@Override
	public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs)
			throws IOException {
		if (onlineCompanyIds == null || onlineCompanyIds.isEmpty()) {
			return new OpenBitSet();
		}
		FieldCache.DocTermsIndex companyIdTermsIndex = FieldCache.DEFAULT
				.getTermsIndex(context.reader(), field.getName());
		OpenBitSet bitSet = new OpenBitSet(context.reader().maxDoc());
		for (int i = 0; i < context.reader().maxDoc(); i++) {
			if (context.reader().hasDeletions())
				continue;
			String companyId = getCompanyId(companyIdTermsIndex, i);
			if (companyId != null && onlineCompanyIds.contains(companyId)) {
				bitSet.fastSet(i);
			}
		}
		return bitSet;
	}

	private String getCompanyId(FieldCache.DocTermsIndex companyIdTermsIndex,
			int doc) {
		return (String) DocumentUtils.getFieldValue(companyIdTermsIndex,
				field.getType(), doc);
	}
}
